const http = require('http')
const fs = require('fs')
const url= require('url')
const querystring = require('querystring')
const split = require('./lib/split')
const {v4:uuid} = require("uuid")
const zlib = require('zlib')

const server = http.createServer((req,res)=>{
    //接收get数据
    let {pathname,query} = url.parse(req.url,true)
    //接收post数据
    let arr = [];
        //接收到数据
    req.on('data',data=>{
        arr.push(data)
    })
        //接收结束
    req.on('end',()=>{
        let data = Buffer.concat(arr)
        let flagloca = data.indexOf('\r\n')
        let flag = data.slice(0,flagloca)
        //1. 按分割符切割数据
        let data_a = data.split(flag)
        data_a.shift()
        data_a.pop()
        //2. 丢弃头尾的\r\n
        let data_b = data_a.map(item=>{
            return item.slice(2,item.length-2)
        })
        //3. 按\r\n\r\n分离获取k-v
        let data_c = {}
        data_b.forEach(item=>{
            let arr = item.split('\r\n\r\n');
            //截取key
            let key_name = arr[0].slice(arr[0].indexOf('name="')+6)
            key_name = key_name.slice(0,key_name.indexOf('"'))
            if(arr[0].indexOf('\r\n')!='-1'){
                //截取文件名
                let file_name = arr[0].slice(arr[0].indexOf('filename="')+('filename="'.length))
                file_name = file_name.slice(0,file_name.indexOf('"'))
                //截取文件类型
                let file_type = arr[0].slice(arr[0].indexOf('Content-Type:')+('Content-Type:'.length)+1)
                data_c[key_name.toString()] = {
                    file:arr[1],
                    filename:file_name.toString(),
                    filetype:file_type.toString()
                }
                //存入upload
                //uuid 文件名
                let uuid_str = uuid().replace(/\-/g,'');
                //取文件后缀名
                let filenameArr = file_name.toString().split(".")
                let suffix = filenameArr[filenameArr.length - 1]
                //组合文件存放路径
                let path = `upload/${uuid_str}.${suffix}`
                //写入文件
                fs.writeFile(path,arr[1],err=>{
                    if(err){
                        throw err;
                    }
                    console.log(file_name.toString()+' 上传成功,上传后地址:'+path)
                })
            }else{
                data_c[key_name.toString()] = arr[1].toString()
            }
        })
        console.log(req.headers)
        console.log(data_c)

        //开始返回数据
        res.write('success')
        //返回结束
        res.end()
    })
    
    
})
server.listen(8080)
